import Setting from "../config/Setting";
import LogFactory from "../log/LogFactory";
import LoginType from "../type/LoginType";
import {Result} from "../type/Result";
import {LoginConstant} from "constant/LoginConstant";
import GlobalHandler from "../global/GlobalHandler";

const {baseUrl,loginUrl} = Setting;
const log = LogFactory.getLog("request") ;

export const requestGet = async <T>(url: string): Promise<Result<T>> => {
    return await fetch(baseUrl + url,{
        headers: getHeaders(),
        method: "GET"
    })
        .then(requestHandler)
        .catch(requestErrorHandler) ;
};
export const requestPut = async <T>(url: string,data:any): Promise<Result<T>> => {
    return await fetch(baseUrl + url,{
        headers: getHeaders(),
        method: "PUT",
        body: JSON.stringify(data),
    })
        .then(requestHandler)
        .catch(requestErrorHandler) ;
};
export const requestPost = async <T> (url: string, data: any): Promise<Result<T>> => {
    return await fetch(baseUrl + url, {
        method: "POST",
        headers: getHeaders(),
        body: JSON.stringify(data) // body data type must match "Content-Type" header
    })
        .then(requestHandler)
        .catch(requestErrorHandler) ;
};
export const requestDelete = async <T> (url: string, data?: any): Promise<Result<T>> => {
    return await fetch(baseUrl + url, {
        method: "DELETE",
        headers: getHeaders(),
        body: JSON.stringify(data) // body data type must match "Content-Type" header
    })
        .then(requestHandler)
        .catch(requestErrorHandler) ;
};
export const loginRequest = async <T> (data: LoginType): Promise<Result<T>> => {
    return await fetch(loginUrl, {
        method: "POST",
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' ,
        },
        body: `username=${data.username}&password=${data.password}`
    })
        .then(requestHandler)
        .catch(requestErrorHandler) ;
} ;
const getHeaders = () => {
    // log.debug("获取请求头",localStorage.getItem(LOGIN.AUTHORIZATION)) ;
    // return {
    //     "Content-Type": "application/json",
    //     "Accept": "application/json",
    //     "Authorization": localStorage.getItem(LOGIN.AUTHORIZATION) as string
    // } ;


    let headers = new Headers() ;
    headers.set("Content-Type","application/json") ;
    headers.set("Accept","application/json") ;
    headers.set("Authorization",localStorage.getItem(LoginConstant.AUTHORIZATION) as string) ;
    headers.append('Cookie', 'name=value');
    return headers ;
} ;
const requestHandler = (res: Response): Promise<any> => {
    if(res.status === 417){
        log.warn("用户请求失败,用户token过期") ;
        GlobalHandler.getInstance().sendWarningMessage("请求失败,用户token过期") ;
        GlobalHandler.getInstance().navigateTo("/login",true) ;
        // throw new Error("用户请求失败,用户token过期") ;
    }
    return res.json() ;
};
const requestErrorHandler = (err: any): Promise<any> => {
    log.error("请求错误",err) ;
    GlobalHandler.getInstance().sendWarningMessage("请求失败,服务器连接错误") ;
    // return Promise.reject(err) ;
    return Promise.resolve(err) ;
} ;

